package com.pig4cloud.pig.common.swagger.support;

import cn.hutool.core.lang.Pair;
import com.bblocks.config.SwaggerDisplayEnum;
import org.springframework.util.ReflectionUtils;
import springfox.documentation.schema.ScalarType;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>Project: bblocks-pro - EnumPluginUtils</p>
 * <p>描述：</p>
 *
 * @Author Zhao [125043150@qq.com]
 * @Date 2024/3/1 16:45
 * @Version 1.0
 * @since 8
 */
public class EnumPluginUtils {
    /**
     * 返回枚举 值和显示名
     * @param enumConstants
     * @param annotation
     * @return
     */
    public static List<Pair<Object,String>> getEnumKeyValues(Object[] enumConstants, SwaggerDisplayEnum annotation){
        List<Pair<Object,String>> enumKeyValues = Arrays
                .stream(enumConstants)
                .filter(Objects::nonNull).map(item -> {
            String keyAttrName = annotation.index();
            String valAttrName = annotation.name();
            Class<?> currentClass = item.getClass();
            Field indexField = ReflectionUtils.findField(currentClass, keyAttrName);
            ReflectionUtils.makeAccessible(indexField);
            Object value = ReflectionUtils.getField(indexField, item);
            Field descField = ReflectionUtils.findField(currentClass, valAttrName);
            ReflectionUtils.makeAccessible(descField);
            Object desc = ReflectionUtils.getField(descField, item);

            return  Pair.of(value, desc.toString());
        }).collect(Collectors.toList());
        return enumKeyValues;
    }

    /**
     * 枚举值 对应类型（目前只支持integer、long、string）
     * @param value
     * @return
     */
    public static Pair<ScalarType,String> getValueType(Object value) {
        if (value instanceof Integer){
            return Pair.of(ScalarType.INTEGER,"Integer");
        }else if(value instanceof Long){
            return Pair.of(ScalarType.LONG,"Long");
        }else if(value instanceof String){
            return Pair.of(ScalarType.STRING,"string");
        }else {
            throw new RuntimeException("不支持的枚举Index类型："+value.getClass().getName());
        }
    }
}